import { UpdateLocation } from "~/lib/server";
import { ActionButton, ButtonGroup, Content, DialogTrigger, Dialog, Heading, Button, TextField, Form, useDialogContainer, DialogContainer } from "@adobe/react-spectrum";
import type { Route } from "./+types/edit";
import { useActionData, useFetcher, redirect } from "react-router";
import { useState } from "react";


export async function clientAction({
    params,
    request,
}: Route.ActionArgs) {

    const formData = await request.formData();
    const updates = Object.fromEntries(formData);
    await UpdateLocation(+params.locationId, updates);

    return redirect(`/locations/${params.locationId}`);
}



export function EditLocation({ location }: { location: Location }) {


    let [isOpen, setOpen] = useState(false);


    let onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        // Prevent default browser page refresh.
        e.preventDefault();

        // Get form data as an object.
        const formData = new FormData(e.currentTarget);

        let data = Object.fromEntries(formData);


        // Submit to your backend API...

        try {
            UpdateLocation(location.id, data);
            setOpen(false);
            return redirect(`/locations/${location.id}`);
        } catch (error) {
            return { error: "error" }
        }
    };

    return (
        <>

            <ActionButton onPress={() => setOpen(true)}>
                编辑
            </ActionButton>
            <DialogContainer onDismiss={() => setOpen(false)}>
                {isOpen &&
                    <Dialog>

                        <Heading>{location.name}</Heading>
                        <Content>
                            <Form onSubmit={onSubmit}>
                                <TextField autoFocus label="名称" name='name' defaultValue={location.name} />


                                <ButtonGroup>
                                    <Button variant="accent" type="submit">修改</Button>
                                    <Button variant="secondary" onPress={() => setOpen(false)}>取消</Button>
                                </ButtonGroup>
                            </Form>



                        </Content>


                    </Dialog>
                }
            </DialogContainer >

        </>
    );
}